﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Mirkuz.Mapping
{
    public class KMLCreator
    {
        XmlTextWriter xtr;
        string filename;
        public KMLCreator(string Filename)
        {
            filename=Filename;
        }

        public void CreateKML()
        {
            xtr = new XmlTextWriter(filename, Encoding.UTF8);

            xtr.WriteStartDocument();
            xtr.WriteStartElement("kml");
            xtr.WriteString(" xmlns=\"http://earth.google.com/kml/2.1\"");
        }

        public void AddPoint(WayPoint w)
        {
            w.StreamToKML(xtr);
        }

        public void AddLine(MapTrack t)
        {
            t.StreamToKML(xtr);
        }

        public void CloseKML()
        {
            xtr.WriteEndElement();
            xtr.WriteEndDocument();
            xtr.Close();
        }
    }

    public class KMLReader
    {
        string filename;

        public List<WayPoint> Waypoints = new List<WayPoint>();
        public List<MapTrack> Tracks= new List<MapTrack>();

        public KMLReader(string Filename)
        { 
            filename=Filename;
        }

        public void Parse()
        {            
            using (XmlTextReader xrd=new XmlTextReader(System.IO.File.OpenText(filename)))
            {
                while (xrd.Read())
                {
                    if (xrd.IsStartElement("Placemark"))
                    {
                        using (XmlReader r = xrd.ReadSubtree())
                        {
                            try
                            {
                                Waypoints.Add(new WayPoint(r));
                            }
                            catch { }
                        }
                    }
                }
            }
        }

    }
}
